import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button, Row, Col } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import DataEditTable from '../../addons/DataEditTable'
import Comp_PaySalaryCorpFhqk from './Comp_PaySalaryCorpFhqk'
import * as compDiviService from '../../../services/AccountDivi';
const daoName = "CompPaySalaryCorp";
const ButtonGroup = Button.Group;
const renderNumber = (num) => {
  let value = ''
  if (num) {
      value = numeral(num).format('0,0')
  }
  return value
};
const columns = [
  { title: '组织机构号', width: 110, sorter: true, dataIndex: 'ZZJG', key: 'ZZJG', dispaly: true, filter: true },
  { title: '代发企业名', width: 240, sorter: true, nowrap: true, key: 'NAME', dispaly: true, filter: true },
  { title: '最近代发月份', width: 140, sorter: true, dataIndex: 'DFYF', key: 'DFYF', dispaly: true, filter: true },
  { title: '累计代发', width: 120, sorter: true, dataIndex: 'LJDF', key: 'LJDF', dispaly: true, filter: true },
  { title: '累计代发金额', width: 150, sorter: true, dataIndex: 'DFJE', key: 'DFJE', dispaly: true, filter: true },
  { title: '客户经理1', width: 100, sorter: false, dataIndex: 'YG1', key: 'YG1', dispaly: true, filter: false },
  { title: '分配比例1(%)', width: 100, sorter: false, className: "column-money", caption: 'ZB1', render: data => renderNumber(data.ZB1), key: 'ZB1', dispaly: true, filter: false },
  { title: '客户经理2', width: 100, sorter: false, dataIndex: 'YG2', key: 'YG2', dispaly: true, filter: false },
  { title: '分配比例2(%)', width: 100, sorter: false, className: "column-money", caption: 'ZB2', render: data => renderNumber(data.ZB2), key: 'ZB2', dispaly: true, filter: false },
  { title: '客户经理3', width: 100, sorter: false, dataIndex: 'YG3', key: 'YG3', dispaly: true, filter: false },
  { title: '分配比例3(%)', width: 100, sorter: false, className: "column-money", caption: 'ZB3', render: data => renderNumber(data.ZB3), key: 'ZB3', dispaly: true, filter: false },
  { title: '客户经理4', width: 100, sorter: false, dataIndex: 'YG4', key: 'YG4', dispaly: true, filter: false },
  { title: '分配比例4(%)', width: 100, sorter: false, className: "column-money", caption: 'ZB4', render: data => renderNumber(data.ZB4), key: 'ZB4', dispaly: true, filter: false },
  { title: '客户经理5', width: 100, sorter: false, dataIndex: 'YG5', key: 'YG5', dispaly: true, filter: false },
  { title: '分配比例5(%)', width: 100, sorter: false, className: "column-money", caption: 'ZB5', render: data => renderNumber(data.ZB5), key: 'ZB5', dispaly: true, filter: false },

];
const columnsWaitDivi = [
  { title: '组织机构号', width: 120, dataIndex: 'ZZJG', key: 'ZZJG', dispaly: true },
  { title: '代发企业名', width: 210, dataIndex: 'NAME', key: 'NAME', dispaly: true }
];
const columnsDivi = [
  { title: '员工ID', dataIndex: 'EMID', key: 'EMID', width: 80, dispaly: false },
  { title: '员工编号', dataIndex: 'EMNO', key: 'EMNO', width: 80, dispaly: true },
  { title: '员工名称', width: 80, sorter: true, dataIndex: 'SysUserName', key: 'SysUserName', dispaly: true },
  { title: '开户机构', width: 80, sorter: true, dataIndex: 'OrganName', key: 'OrganName', dispaly: true },
  { title: '分户日期', width: 80, sorter: true, key: 'DSDT', caption: "DSDT", render: data => datetime.format(data.DSDT, "yyyy-MM-dd"), dispaly: true },
  { title: '分户值(%)', width: 80, sorter: true, dataIndex: 'DSVL', key: 'DSVL', dispaly: true },
];
const controls = [
  { name: 'ZZJG', required: true, type: 'text', label: '组织机构号', grid: 12 / 24 },
  { name: 'NAME', required: true, type: 'text', label: '代发企业名', grid: 12 / 24 },
  { name: 'DFYF', required: true, type: 'text', label: '最近代发月', grid: 12 / 24 },
  { name: 'LJDF', required: true, type: 'text', label: '累计代发', grid: 12 / 24 },
  { name: "DFJE", label: "累计代发金额", type: 'number', grid: 12 / 24, dataType: "number" },
];
const controlsWaitDivi = [
  { name: 'ZZJG', required: true, type: 'text', label: '组织机构号', grid: 12 / 24 },
  { name: 'NAME', required: true, type: 'text', label: '代发企业名', grid: 12 / 24 }
];
const controlsDivi = [
  { name: 'EMID', required: true, type: 'number', label: '员工编号', grid: 12 / 24, dataType: "number" },
  { name: 'EMNO', required: true, type: 'alphanum', label: '员工编号', grid: 12 / 24 },
  { name: 'SysUserName', required: true, type: 'text', label: '员工名称', grid: 12 / 24 },
  { name: 'OrganName', required: true, type: 'text', label: '开户机构', grid: 12 / 24 },
  { name: "DSDT", required: true, type: "date", label: "分户日期", grid: 12 / 24, dataType: "date" },
  { name: "DSVL", required: true, type: "number", label: '分户值', grid: 12 / 24, dataType: "number" },
];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class Comp_PaySalaryCorpForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false,
      diviList: [],
      diviDisplay: {
        div1: 'block',
        div2: 'none',
        lable: '认定',
        isRD: true,
        isDivi:false
      },
      searchData: {},
      diviDataSource: []
    };
  }
  componentWillReceiveProps(nextProps) {
  }; 
  onSelectChangeHandler(newList,delKeys){
    let diviList=this.state.diviList
    newList.map(data=>{
      diviList.push(data)
    })
    delKeys.map(key=>{
      const index=diviList.findIndex(divi=>divi["ID"]===key)
      diviList.splice(index, 1)
    })
    this.setState({diviList})
  }
  componentDidMount() {
    this.props.dispatch({
      type: `${daoName}/setKeyName`,
      payload: { keyName: "ID", permID: this.props.permID }
    });
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, page: 1, pageSize: 20 }
    });
    this.loadOptionData();
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  findData() {
    let zzjg = '';
    let name = '';
    const form = this.refs.findForm.getForm();
    form.validateFields((err, values) => {
      if (!err) {
        if (values.ZZJG === undefined) {
          values.ZZJG = ""
        }
        if (values.NAME === undefined) {
          values.NAME = ""
        }
        zzjg = values.ZZJG;
        name = values.NAME
      }
    });
    let seeks = [];
    let whereItems = [];
    let WhereCauses = [];
    if (zzjg !== '' && name === '') {
      whereItems.push({
        FieldName: "ZZJG",
        Operator: "like",
        FieldValues: zzjg
      });
    } else if (zzjg === '' && name !== '') {
      whereItems.push({
        FieldName: "NAME",
        Operator: "like",
        FieldValues: name
      });
    } else {
      whereItems.push({
        FieldName: "ZZJG",
        Operator: "like",
        FieldValues: zzjg
      });
      whereItems.push({
        FieldName: "NAME",
        Operator: "like",
        FieldValues: name
      });
    }
    WhereCauses.push({
      WhereItems: whereItems,
      RelationSign: "AND"
    })
    seeks = WhereCauses;    
    this.state.diviDisplay.div1 = 'block';
    this.state.diviDisplay.div2 = 'none';
    this.state.diviDisplay.lable = '认定';
    this.state.diviDisplay.isRD = true;
    this.state.diviDisplay.isDivi=false;
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, seeks }
    });
  };
  dispalyDivi() {
    if (this.state.diviDisplay.isRD) {
      this.state.diviDisplay.div1 = 'none';
      this.state.diviDisplay.div2 = 'block';
      this.state.diviDisplay.lable = '返回';
      this.state.diviDisplay.isRD = false;
      this.state.diviDisplay.isDivi=true;
      this.state.diviList = [];
      this.props.dispatch({
        type: `${daoName}/setSelectedRowKeys`,
        payload: { selectedRowKeys: [] }
      });
    } else {
      this.state.diviDisplay.div1 = 'block';
      this.state.diviDisplay.div2 = 'none';
      this.state.diviDisplay.lable = '认定';
      this.state.diviDisplay.isRD = true;
      this.state.diviDisplay.isDivi=false;
      this.state.diviList = [];
      this.props.dispatch({
        type: `${daoName}/setSelectedRowKeys`,
        payload: { selectedRowKeys: [] }
      });
    }
  };
  searchHandle(data) {
    this.state.searchData = data
  };
  diviAdd() {
    let data = {}
    let formatDate = null
    const form = this.refs.diviForm.getForm();
    let isOK = true;
    form.validateFields((err, values) => {
      if (!err) {
        if (values.ZB === undefined || values.ZB === '') {
          message.info('占比不能为空！');
          isOK = false;
        }
        if (values.YG === undefined || values.YG === '') {
          message.info('员工不能为空！');
          isOK = false;
        }
        if (values.YF === undefined) {
          message.info('月份不能为空！');
          isOK = false;
        }
        if (values.ZB === undefined) {
          values.ZB = '';
        }
        if (values.YF === undefined) {
          values.YF = '';
        }
        if (values.YF !== '') {
          formatDate = new Date(values.YF.get('year'), values.YF.get('month'), 1, 8, 0, 0)
        }
        data.DSVL = Number(values.ZB);
        data.DSDT = values.YF === !values.YF ? null : formatDate
      }
    });
    if (!isOK) {
      return;
    }
    if (this.state.searchData.ID < 0 || this.state.searchData.No.indexOf(":") > 0) {
      message.error('分配失败！员工：' + this.state.searchData.Name + '为虚拟员工，不支持业绩分配！请重新选择')
      return;
    }
    data.EMID = this.state.searchData.ID;                    //员工ID
    data.EMNO = this.state.searchData.No;                    //员工编号
    data.SysUserName = this.state.searchData.Name;           //员工名称
    data.OrganName = this.state.searchData.Organization.Name;//开户机构
    let diviDs = this.state.diviDataSource
    let diviSum = data.DSVL;
    diviDs.map(d => diviSum += d.DSVL)
    if (diviSum > 100) {
      message.info('占比不能大于100！');
      return;
    }
    diviDs.push(data);
    this.setState({ diviDataSource: diviDs });
  };
  diviDel() {
    let keys = this.refs.table3.getSelectedRowKeys();
    keys.sort();
    const datas = this.refs.table3.state.datas;
    let indexs = [];
    const keyName = 'EMID'
    datas.map((d, k) => {
      for (let i = 0; i < keys.length; i++) {
        if (d[keyName] === keys[i]) {
          indexs.push(k)
        }
      }
    })
    let diviDsource = this.state.diviDataSource;
    for (let j = indexs.length - 1; j >= 0; j--) {
      const k = indexs[j]
      diviDsource.splice(k, 1)
    }
    this.setState({ diviDataSource: diviDsource })
  };
  diviSubmit() {
    const datas = this.refs.table3.state.datas;
    const witDividatas = this.refs.table2.state.datas;
    if (witDividatas.length <= 0) {
      message.info('请选择要认定的代发单位!');
      return;
    }
    let dsvlSum = 0;
    let dataSource = []
    datas.map(d => {
      dsvlSum = dsvlSum + d.DSVL;
      let data = {
        EMID: Number(d.EMID),
        DSDT: d.DSDT,
        DSVL: Number(d.DSVL) / 100
      }
      dataSource.push(data);
    })
    if (dsvlSum !== 100) {
      message.info('占比必须为100%');
      return;
    }
    let acids = [];
    witDividatas.map(d => acids.push(Number(d.ID)))
    Modal.confirm({
      title: '提示',
      content: `你确认要认定给 ${datas.map(d => d.SysUserName)} 吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        compDiviService.dfdwDivi({ acids, dataSource }
        ).then(function (data) {
          if (data === 'OK') {
            message.success('数据认定成功！')
          } else {
            return;
          }
        }).catch(function (ex) {
          console.log('请求出错', ex)
        });
        this.state.diviDisplay.div1 = 'block';
        this.state.diviDisplay.div2 = 'none';
        this.state.diviDisplay.lable = '认定';
        this.state.diviDisplay.isRD = true;
        this.state.diviDisplay.isDivi=false;
        this.state.diviDataSource = [];
        this.state.diviList = [];
        const form = this.refs.diviForm.getForm();
        form.resetFields();
        this.props.dispatch({
          type: `${daoName}/setSelectedRowKeys`,
          payload: { selectedRowKeys: [] }
        });
      }
    });
  }
  render() {
    let { showEdit, record, offsetHeight,permID, popedomTypes } = this.props;
    let table1Height = (offsetHeight - 133) * 0.5-70 
    let data=[{ value: '1', label: '查询', onClick: this.findData.bind(this) }]
    let pTypes = popedomTypes[permID]
    // if(pTypes.indexOf("6")!==-1){
    //   data.push({ value: '2', label: this.state.diviDisplay.lable, onClick: this.dispalyDivi.bind(this) })
    // }  
    let dataList = this.state.diviList;
    const dsCount = this.state.diviDataSource.length
    const isDisabled = dsCount > 0 ? true : false;
    const controlsFilter = [
      { name: 'ZZJG', required: false, type: 'text', label: '组织机构号', grid: 8 / 24, layout: { labelSpan: 6, wrapperSpan: 18 } , placeholder: '请输入组织机构号...'},
      { name: 'NAME', required: false, type: 'text', label: '代发企业', grid: 8 / 24, placeholder: '请输入代发企业名...' },
      { name: 'BT', required: false, type: 'button-group', data: data, grid: 4 / 24 },
    ];
    const controlsDivi2 = [
      { name: 'YG', required: false, type: 'search', label: '员工', grid: 5 / 24, layout: { labelSpan: 8, wrapperSpan: 15 }, fetch: { daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID", onSelect: this.searchHandle.bind(this) } },
      { name: 'ZB', required: false, type: 'text', label: '占比(%)', grid: 4 / 24, layout: { labelSpan: 15, wrapperSpan: 9 } },
      { name: 'YF', required: false, type: 'month', label: '月份', grid: 5 / 24, isDisabled: isDisabled, layout: { labelSpan: 8, wrapperSpan: 14 } },
      { name: 'BT', required: false, type: 'button-group', data: [{ value: '1', label: '添加', onClick: this.diviAdd.bind(this) }, { value: '2', label: '删除', onClick: this.diviDel.bind(this) }, { value: '3', label: '提交', onClick: this.diviSubmit.bind(this) }], grid: 10 / 24 },
    ];
    return (
      <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
        <div>
          <div className={styles.create}>
            {/* <EditFrom ref="findForm" daoName={daoName} controls={controlsFilter} selectFirst={false} clearItemMargin={true} /> */}
          </div>
          <DataTable ref="table1" daoName={daoName} columns={columns} controls={controls} canExport={false} multiSelect={this.state.diviDisplay.isDivi} onSelectChange={this.onSelectChangeHandler.bind(this)} permID={permID}/>
          <div style={{ display: this.state.diviDisplay.div2 }}><Comp_PaySalaryCorpFhqk /></div>
          <div style={{ display: this.state.diviDisplay.div2 }}>
            <Row>
              <Col span={10} style={{ paddingRight: 5 }}>
                <DataEditTable columns={columnsWaitDivi} ref="table2" height={table1Height} controls={controlsWaitDivi}
                  dataSource={dataList} keyName={"ID"} daoName={daoName} reload={true}
                />
              </Col>
              <Col span={14}>
                <DataEditTable columns={columnsDivi} ref="table3" height={table1Height}
                  dataSource={this.state.diviDataSource} footer={false} keyName={"EMID"}
                />
                <EditFrom ref="diviForm" daoName={daoName} controls={controlsDivi2} />
              </Col>
            </Row>
          </div>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  const { showEdit, record, selectedRowKeys, keyName, list } = state[daoName];
  const { offsetHeight, userID, orgID, pOrgID, popedomTypes } = state.menus
  return {
    userID,
    orgID,
    pOrgID,
    popedomTypes,
    showEdit,
    selectedRowKeys,
    keyName,
    record,
    offsetHeight,
    list
  }
}
Comp_PaySalaryCorpForm = connect(mapStateToProps)(Comp_PaySalaryCorpForm)
export default Comp_PaySalaryCorpForm;

let render = (props) => React.createElement(Comp_PaySalaryCorpForm, props);
let f = new Factory()
f.set("Comp_PaySalaryCorpForm", render)
